{-# OPTIONS -Wall #-}

--------------------------------------------------------------------------------
-- |
-- Module      :  P5Hs.CLI
-- Copyright   :  (c) Stephen Tetley 2014
-- License     :  BSD3
--
-- Maintainer  :  stephen.tetley@gmail.com
-- Stability   :  unstable
-- Portability :  GHC
--
-- Helpers for running from command line.
-- 
--------------------------------------------------------------------------------

module P5Hs.CLI
  ( 

    ProgramText
  , CLISetup(..)
  , createSketch
  , runSketch
  ) where


import Control.Monad

import System.Directory
import System.Exit
import System.FilePath
import System.Process


type ProgramText = String

data CLISetup = CLISetup
    { path_to_processing_java   :: FilePath
    , sketch_name               :: String
    , output_root               :: FilePath
    }

createSketch :: CLISetup -> ProgramText -> IO ()
createSketch setup src = do
    exists <- doesDirectoryExist sketch_path
    when (not exists) $ createDirectory sketch_path
    writeFile path_to_pde src
  where
    sketch_path = output_root setup </> sketch_name setup
    path_to_pde = sketch_path </> sketch_name setup <.> "pde"



runSketch :: CLISetup -> IO (ExitCode)
runSketch setup = do
    (_,_,_,phand) <- createProcess (proc p5java args)
    exit          <- waitForProcess phand
    return exit
  where
    p5java        = path_to_processing_java setup
    sketch_path   = output_root setup </> sketch_name setup
    out_path_temp = output_root setup </> (sketch_name setup ++ "-out")
    args          = [ "--run"
                    , "--sketch=" ++ sketch_path
                    , "--force"
                    , "--output=" ++ out_path_temp
                    ]

{-

runSketch :: CLISetup -> IO (ExitCode)
runSketch setup = do
    (exit,_,_) <- readProcessWithExitCode procj args ""
    return exit
  where
    procj         = path_to_processing_java setup
    sketch_path   = output_root setup </> sketch_name setup
    out_path_temp = output_root setup </> (sketch_name setup ++ "-out")
    args          = [ "--run"
                    , "--sketch=" ++ sketch_path
                    , "--force"
                    , "--output=" ++ out_path_temp
                    ]

-}